import { getToken, setToken, removeToken } from '@/utils/auth'
import api from '@/api'
import request from '@/utils/request'
import { expendsTree, generateTree } from '@/utils'

const user = {
  state: {
    user: {},
  },

  mutations: {
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_SUB_MENU: (state, id) => {
      let tmp = state.user.menus.find(v => v.id == id)
      if (tmp && tmp.children) {
        state.user.subMenus = tmp.children
      } else {
        state.user.subMenus = [tmp]
      }
    },
  },

  actions: {
    // 用户登录
    LoginByUsername({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        request(
          api.login,
          {
            username: userInfo.username.trim(),
            password: userInfo.password.trim(),
            client: 'WEB',
          },
          'post',
        )
          .then(r => {
            setToken(r.token)
            resolve()
          })
          .catch(e => {
            reject(e)
          })
      })
    },
    //企业微信授权码登录
    LoginByWxcode({ commit }, code) {
      return new Promise((resolve, reject) => {
        request(`${api.qywxLogin}?code=${code}`, {}, 'post', true)
          .then(r => {
            setToken(r.token)
            resolve()
          })
          .catch(e => {
            reject(e)
          })
      })
    },
    //获取用户信息
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        request(api.userInfo, { client: 'WEB' })
          .then(r => {
            let user = r.user || {}
            let tmp = expendsTree(r.menu, 'children')
            //后端返回的所有菜单数据 包含win和web
            user.menu = tmp.map(x => {
              return {
                id: x.id,
                resource_type: x.resource_type,
                parent: x.parent_id,
                icon: x.icon,
                title: x.menu_name,
                desc: x.menu_desc,
                target: x.path,
                is_visible: x.is_visible,
                power_codes: x.power_codes,
              }
            })
            //组成web端的菜单树
            user.menus = generateTree(
              user.menu.filter(x => x.resource_type != 'WIN'),
              'id',
              'parent',
              '0',
            )
            //先加载首页菜单 后面再优化 TODO
            if (user.menus.length > 0 && user.menus[0].children && user.menus[0].children[0].target == 'welcome') {
              user.menus[0].children.push(...user.menus.filter(x => x.parent == '0' && x.id != user.menus[0].id))
            }
            //左侧菜单，相当于是二级
            user.subMenus = []
            commit('SET_USER', user)
            resolve()
          })
          .catch(e => {
            reject(e)
          })
      })
    },
    //修改密码
    ChangePass({ commit }, data) {
      return new Promise((resolve, reject) => {
        request(
          api.changePass,
          {
            userId: data.userID,
            newPassword: data.new_password,
            oldPassword: data.old_password,
          },
          'post',
        )
          .then(r => {
            resolve()
          })
          .catch(e => {
            reject(e)
          })
      })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        removeToken()
        commit('SET_USER', {})
        resolve()
      })
    },
  },
  getters: {
    user: state => state.user,
  },
}

export default user
